package com.kasax.imgloader.v1.utils;

import android.os.Build;
import android.os.Environment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class FileUtils {

    public static String getSafeSdcardPath(String src) {
        String result = src;
        if (src.startsWith("/mnt/sdcard")) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                // 针对android 11以上的处理
                String storageDirPath = Environment.getExternalStorageDirectory().getPath();
                String newPath = src.replace("/mnt/sdcard", storageDirPath);
                result = newPath;
            }
        }
        LogUtils.e("getSafeSdcardPath result = " + result);
        return result;
    }

    /**
     * 写入文件
     */
    public static void write(String data, String filePath) {
        LogUtils.e("FileUtils write exec");
        File tFile = new File(filePath);
        try {
            if (!tFile.exists()) {
                tFile.createNewFile();
            }
            try (FileWriter fw = new FileWriter(tFile)) {
                fw.write(data);
                fw.flush();
                fw.close();
                LogUtils.e("FileUtils write exec complete");
            } catch (Throwable e) {
                LogUtils.e(e.getMessage());
            }
        } catch (Throwable e) {
            LogUtils.e(e.getMessage());
        }
    }

    /**
     * 读取文件
     *
     * @param filePath
     * @return
     */
    public static String readString(String filePath) {
        LogUtils.e("FileUtils readString exec");
        File tFile = new File(filePath);
        StringBuilder sb = new StringBuilder();
        if (!tFile.exists()) {
            return sb.toString();
        }
        try (BufferedReader br = new BufferedReader(new FileReader(tFile))) {
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            LogUtils.e("FileUtils readString exec compile");
        } catch (Throwable e) {
            LogUtils.e(e.getMessage());
        }
        return sb.toString();
    }


}
